import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';
import 'LoadView.dart';

class FullScreen extends StatefulWidget {
  final VideoPlayerController controller;
  final bool play;

  const FullScreen({Key key, this.controller, this.play}) : super(key: key);

  @override
  _FullScreenState createState() => _FullScreenState();
}

class _FullScreenState extends State<FullScreen> {
  VideoPlayerController _controller;
  bool play = false;
  Function _function;
  Timer timer;
  var initialize;
  bool needRotated = false;

  @override
  void initState() {
    super.initState();
    _controller = widget.controller;
    needRotated = _controller.value.size.width > _controller.value.size.height;
    _function = () {
      if (!mounted) {
        return;
      }
      var duration = _controller.value.duration;
      var position = _controller.value.position;
      if (position.inMilliseconds > 0 && duration.compareTo(position) == 0) {
        setState(() {
          play = false;
        });
      }
    };
    _controller.addListener(_function);
    if (needRotated) {
      // SystemChrome.setPreferredOrientations(
      //     [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    } else {
      SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
    }
    timer = Timer.periodic(Duration(seconds: 1), (timer) {
      try {
        if (play) {
          setState(() {});
        }
      } catch (e) {
        timer.cancel();
      }
    });
    if (widget.play == true) {
      play = true;
      _controller.play();
    }
    initialize = getInitialize();
  }

  @override
  void dispose() {
    super.dispose();
    _controller.removeListener(_function);
    timer?.cancel();
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
    print('-----------销毁------------');
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        // 旋转屏幕会使ScreenUtil样式错乱, 暂时用旋转组件替换
        child: RotatedBox(
          quarterTurns: needRotated ? 1 : 0,
          child: Scaffold(
            backgroundColor: Colors.black,
            body: Stack(
              children: <Widget>[
                Center(
                    child: FutureBuilder(
                        future: initialize,
                        builder:
                            (BuildContext context, AsyncSnapshot snapshot) {
                          //请求完成
                          if (snapshot.connectionState ==
                              ConnectionState.done) {
                            //发生错误
                            if (snapshot.hasError) {
                              debugPrint(snapshot.error.toString());
                              return Center(
                                  child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  IconButton(
                                      icon: Icon(
                                        Icons.error_outline,
                                        color: Colors.white,
                                      ),
                                      onPressed: () {
                                        setState(() {
                                          initialize = getInitialize();
                                        });
                                      }),
                                  Text(
                                    "视频加载失败",
                                    style: TextStyle(color: Colors.white),
                                  )
                                ],
                              ));
                            }
                            return Stack(
                              children: <Widget>[
                                Center(
                                  child: GestureDetector(
                                    child: Container(
                                      width: geWidth(_controller.value),
                                      height: getHeight(_controller.value),
                                      child: VideoPlayer(_controller),
                                    ),
                                    onTap: () {
                                      setState(() {
                                        play = false;
                                        _controller.pause();
                                      });
                                    },
                                  ),
                                ),
                                Visibility(
                                  child: Center(
                                    child: IconButton(
                                        icon: Icon(
                                          Icons.play_circle_outline,
                                          size: 40,
                                          color: Colors.white,
                                        ),
                                        onPressed: () {
                                          play = true;
                                          var duration =
                                              _controller.value.duration;
                                          var position =
                                              _controller.value.position;
                                          if (position.inMilliseconds > 0 &&
                                              duration.compareTo(position) ==
                                                  0) {
                                            _controller.seekTo(Duration());
                                            setState(() {});
                                            return;
                                          }
                                          _controller.play();
                                          setState(() {});
                                        }),
                                  ),
                                  visible: !play,
                                ),
                                Positioned(
                                  child: Visibility(
                                      child: Container(
                                    child: LinearProgressIndicator(
                                      backgroundColor: Colors.white10,
                                      value: getProgress(),
                                    ),
                                    height: 3,
                                    width: double.infinity,
                                  )),
                                  bottom: 0,
                                  left: 0,
                                  right: 0,
                                )
                              ],
                            );
                          }
                          return LoadView();
                        })),
                Positioned(
                  child: Container(
                    height: 50,
                    alignment: Alignment.centerLeft,
                    child: BackButton(
                      color: Colors.white,
                    ),
                  ),
                  // AppBar(
                  //   backgroundColor: Colors.transparent,
                  //   elevation: 0,
                  //   leading: BackButton(
                  //       color: Colors.white,
                  //       onPressed: () {
                  //         SystemChrome.setPreferredOrientations([
                  //           DeviceOrientation.portraitDown,
                  //           DeviceOrientation.portraitUp
                  //         ]).then((value) => Navigator.of(Get.context).pop());
                  //       }),
                  // ),
                  top: 0,
                  right: 0,
                  left: needRotated ? MediaQuery.of(context).padding.top : 0,
                )
              ],
            ),
          ),
        ),
        onWillPop: () async {
          // 点击返回键的操作
          SystemChrome.setPreferredOrientations(
              [DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
          return true;
        });
  }

  double geWidth(VideoPlayerValue value) {
    Size size = MediaQuery.of(context).size;
    var aspectRatio = value.aspectRatio;
    double height = getHeight(value);
    double width = height * aspectRatio;
    double mWidth = needRotated ? size.height : size.width;
    if (width > mWidth) {
      width = mWidth;
    }
    return width;
  }

  double getHeight(VideoPlayerValue value) {
    Size size = MediaQuery.of(context).size;
    double height = needRotated ? size.width : size.height;
    if (value.size.height < height) {
      height = value.size.height;
    }
    return height;
  }

  getProgress() {
    var duration = _controller.value.duration;
    var position = _controller.value.position;
    return position.inSeconds / duration.inSeconds;
  }

  getInitialize() {
    var initialized = _controller.value.isInitialized;
    return initialized
        ? Future(() {
            return null;
          })
        : _controller.initialize();
  }
}
